package com.muyan.sys.webscoket.listener;

import com.alibaba.fastjson2.JSON;
import com.muyan.sys.webscoket.service.ChatGroupService;
import com.muyan.sys.webscoket.util.ChannelManager;
import com.muyan.sys.webscoket.protocol.MessageProto;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Slf4j
@Component
public class GroupChatMessageListener {
    @Autowired
    private  ChannelManager channelManager;
    @Autowired
    private  ChatGroupService chatGroupService;
    

    /**
     * 动态监听队列
     * 监听群聊消息队列
     */
    @RabbitListener(queues = "#{groupChatQueue.name}", containerFactory = "mqConsumerListenerFactory")
    public void handleGroupChatMessage(String message) {
        try {
            MessageProto groupMessage = JSON.parseObject(message, MessageProto.class);
            String groupId = groupMessage.getGroupId();
            log.info("群聊: {}", message);
            // 获取群组成员
            Set<String> groupMembers = chatGroupService.getGroupMembers(groupId);
            if (groupMembers == null) {
                return;
            }

            // 转发消息给群组在线成员
            for (String userId : groupMembers) {
                Channel userChannel = channelManager.getChannel(userId);
                if (userChannel != null && userChannel.isActive()) {
                    userChannel.writeAndFlush(new TextWebSocketFrame(message));
                }
            }
            log.info("群消息已转发到群组: {}", groupId);
        } catch (Exception e) {
            log.error("处理群聊消息异常", e);
        }
    }
} 